package com.zq.多线程设计模式.多线程打印奇偶数;

/**
 * @author Jiu
 * @description：多线程打印奇偶数
 * @date 2021/04/07   10:07
 **/
public class TwoThreadWaitNotify {


    private int start = 0;

    private boolean flag = false;

    public static void main(String[] args) {
        TwoThreadWaitNotify twoThreadWaitNotify = new TwoThreadWaitNotify();
        Thread t1 = new Thread(new JiNUmber(twoThreadWaitNotify));
        t1.setName("t111111");
        Thread t2 = new Thread(new OuNUmber(twoThreadWaitNotify));
        t2.setName("p000000");
        t1.start();
        t2.start();

    }


    public static class JiNUmber implements Runnable{

        private TwoThreadWaitNotify twoThreadWaitNotify;

        public JiNUmber(TwoThreadWaitNotify twoThreadWaitNotify) {
            this.twoThreadWaitNotify = twoThreadWaitNotify;
        }

        @Override
        public void run() {
            while (twoThreadWaitNotify.start<100){
             synchronized (TwoThreadWaitNotify.class){
                 System.out.println("抢到线程了" +twoThreadWaitNotify.flag );
                 if (twoThreadWaitNotify.flag){
                     System.out.println(Thread.currentThread().getName()+"+++++"+twoThreadWaitNotify.start);
                     twoThreadWaitNotify.start++;
                     twoThreadWaitNotify.flag = false;

                     TwoThreadWaitNotify.class.notify();
                 }else {
                     try {
                         Thread.sleep(10);
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }
                 }
             }
            }
        }
    }
    public static class OuNUmber implements Runnable{

        private TwoThreadWaitNotify twoThreadWaitNotify;

        public OuNUmber(TwoThreadWaitNotify twoThreadWaitNotify) {
            this.twoThreadWaitNotify = twoThreadWaitNotify;
        }

        @Override
        public void run() {
            while (twoThreadWaitNotify.start<100){
                synchronized (TwoThreadWaitNotify.class){
                    System.out.println("抢到线程了" +twoThreadWaitNotify.flag );
                    if (!twoThreadWaitNotify.flag){
                        System.out.println(Thread.currentThread().getName()+"----------------------------"+twoThreadWaitNotify.start);
                        twoThreadWaitNotify.start++;
                        twoThreadWaitNotify.flag = true;

                        TwoThreadWaitNotify.class.notify();
                    }else {
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}


